using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MiniTheme.Services.Interfaces;
using MiniTheme.Views;
using MiniTheme.Views.Pages;

namespace MiniTheme.Services;

public class ApplicationHostService : IHostedService
{
    private readonly IServiceProvider _serviceProvider;
    public ApplicationHostService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await InitializeAsync();
    }
    public Task StopAsync(CancellationToken cancellationToken)
    {
        var monitor = _serviceProvider.GetRequiredService<ISystemThemeMonitor>();
        monitor.StopMonitoring();
        return Task.CompletedTask;
    }
    private Task InitializeAsync()
    {
        return Application.Current.Dispatcher.InvokeAsync(() =>
        {
            // 应用保存的语言设置
            var languageService = _serviceProvider.GetRequiredService<ILanguageService>();
            var configService = _serviceProvider.GetRequiredService<IConfigService>();
            languageService.ApplyLanguage(configService.GetLanguage());
            // 应用保存的主题设置
            var themeService = _serviceProvider.GetRequiredService<IThemeService>();
            themeService.ApplyTheme(themeService.GetCurrentThemeMode());
            // 启动系统主题监控
            var monitor = _serviceProvider.GetRequiredService<ISystemThemeMonitor>();
            monitor.StartMonitoring();
            // 显示主窗口
            var mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
            mainWindow.Show();
            // 初始导航到默认视图
            var navigationService = _serviceProvider.GetRequiredService<INavigationService>();
            navigationService.NavigateTo<ThemeView>();
        }).Task;
    }
}
